package my.jwds.p417;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PacificAtlantic {

    public static void main(String[] args) {

        Solution obj = new Solution();
        int [][] heights = JSONObject.parseObject("[[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]",int[][].class);
        long start = System.currentTimeMillis();
        System.out.println(obj.pacificAtlantic(heights));
        System.out.println("运行时间:" + (System.currentTimeMillis() - start));
    }

    static class Solution {

        int [][] heights;
        int [][] results;
        int m,n;
        public List<List<Integer>> pacificAtlantic(int[][] heights) {
            this.heights = heights;
            m = heights.length;
            n = heights[0].length;
            results = new int[m][n];
            for (int i = 0; i < m; i++) {
                dfs(i,0,1);
                dfs(i,n-1,2);
            }
            for (int i = 0; i < n; i++) {
                dfs(0,i,1);
                dfs(m-1,i,2);
            }
            List<List<Integer>>res = new ArrayList<>();
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (results[i][j] == 3){
                        List<Integer> list = new ArrayList<>();
                        list.add(i);
                        list.add(j);
                        res.add(list);
                    }
                }
            }
            return res;

        }

        void dfs(int y,int x,int a){
            if ((results[y][x] & a) == a){
                return;
            }
            results[y][x] |= a;
            if (y != m-1 && heights[y][x] <= heights[y+1][x]){
                dfs(y+1,x,a);
            }

            if (y != 0 && heights[y][x] <= heights[y-1][x]){
                dfs(y-1,x,a);
            }

            if (x != n-1 && heights[y][x] <= heights[y][x+1]){
                dfs(y,x+1,a);
            }

            if (x != 0 && heights[y][x] <= heights[y][x-1]){
                dfs(y,x-1,a);
            }
        }

    }
}